<?php

namespace App\Http\Controllers\Personal;

use App\Http\Requests\Personal\SearchEngine\CreateSearchEngineRequest;
use App\Http\Requests\Personal\SearchEngine\UpdateSearchEngineRequest;
use App\Models\Common\CollTown;
use App\Models\Common\CollArea;
use App\Models\Common\CollPosition;
use App\Models\Common\CollOption;
use App\Models\Personal\SearchEngine;
use App\Models\XS\JobXS;
use Illuminate\Http\Request;
use App\Models\Personal\Resume;
use Illuminate\Support\Facades\DB;
use Style;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;

class SearchEngineController extends CommonController{

    /**
     * 精确搜索
     * @param Request $request
     * @return mixed
     */
    public function accurateSearch(Request $request){
        $user = auth()->guard('personal')->user();
        if($request->isMethod('post')){
            $input = $request->except('_token', 'workplace', 'jobsort', 'industry', 'sub');
            $company_job = DB::table('company_job as t1')
                ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
                //获取字段
                ->select(
                    't1.id', 't1.com_id', 't1.job_title', 't1.industry',
                    't1.job_category1', 't1.job_category2', 't1.job_category3', 't1.job_category4', 't1.job_category5',
                    't1.location1', 't1.location2', 't1.location3', 't1.location4', 't1.location5',
                    't1.recruiting_num', 't1.salary_above', 't1.salary_below', 't1.description',
                    't1.education', 't1.work_year', 't1.age_above', 't1.age_below', 't1.gender', 't1.updatetime',
                    't2.company_name', 't2.region', 't2.industry', 't2.address'
                )
                //岗位类别
                ->where(function($query) use ($input){
                    for($i = 1; $i <= 5; $i++){
                        if(!empty($input['jobsort' . $i]))
                            $query->orWhere('t1.job_category1', '=', $input['jobsort1'])
                                ->orWhere('t1.job_category2', '=', $input['jobsort2'])
                                ->orWhere('t1.job_category3', '=', $input['jobsort3'])
                                ->orWhere('t1.job_category4', '=', $input['jobsort4'])
                                ->orWhere('t1.job_category5', '=', $input['jobsort5']);
                        else break;
                    }
                })
                //工作地点
                ->where(function($query) use ($input){
                    for($i = 1; $i <= 5; $i++){
                        if(!empty($input['jobarea' . $i]))
                            $query->orWhere('t1.location1', '=', $input['jobarea1'])
                                ->orWhere('t1.location2', '=', $input['jobarea2'])
                                ->orWhere('t1.location3', '=', $input['jobarea3'])
                                ->orWhere('t1.location4', '=', $input['jobarea4'])
                                ->orWhere('t1.location5', '=', $input['jobarea5']);
                        else break;
                    }
                })
                //所属行业
                ->where(function($query) use ($input){
                    for($i = 1; $i <= 5; $i++){
                        if(!empty($input['industry' . $i])) $query->orWhere('t1.industry', '=', $input['industry' . $i]);
                        else break;
                    }
                })
                //性别要求
                ->where(function($query) use ($input){
                    if(!empty($input['sex'])) $query->where('t1.gender', '=', $input['sex']);
                })
                //学历要求
                ->where(function($query) use ($input){
                    if(!empty($input['education'])) $query->where('t1.education', '>=', $input['education']);
                })
                //年龄要求 当前所选大于或者等于年龄以上的
                ->where(function($query) use ($input){
                    if(!empty($input['age'])) $query->where('t1.age_above', '>=', $input['age']);
                })
                //工作经验 当前所选工作经验以上
                ->where(function($query) use ($input){
                    if(!empty($input['work_year'])) $query->where('t1.work_year', '>=', $input['work_year']);
                })
                //关键字
                ->where(function($query) use ($input){
                    if(!empty($input['keyword'])){
                        if($input['keyword_type'] == '1'){
                            //全文搜索时？？？？
                        }elseif($input['keyword_type'] == '2'){
                            $query->where('t1.job_title', 'like', '%' . $input['keyword'] . '%');
                        }elseif($input['keyword_type'] == '3'){
                            $query->where('t2.company_name', 'like', '%' . $input['keyword'] . '%');
                        }
                    }
                })
                //发布日期
                ->where(function($query) use ($input){
                    if(!empty($input['release_date'])){
                        //获取选中的多少时间内
                        $ctime = date("Y-m-d H:i:s", strtotime("-" . $input['release_date'] . "day"));
                        $query->where('t1.updatetime', '>=', $ctime);
                    }
                })
                ->paginate(10);
            //精确搜索已经全部写好
            //dd($company_job);
            //return Style::view('personal.accurateSearch');
        }else{
            return Style::view('personal.accurateSearch');
        }
    }

    /**
     * 搜索器列表
     * @return mixed
     */
    public function index(){
        $user = auth()->guard('personal')->user();
        $searchEngine = SearchEngine::where('uid', $user->uid)->orderBy('updated_at', 'desc')->paginate(10);
        foreach($searchEngine as $k => $v){
            $alinks = arrayFilter(array(
                "jobsort1" => !empty($v->jobsort1) ? $v->jobsort1 : '',
                "jobsort2" => !empty($v->jobsort2) ? $v->jobsort2 : '',
                "jobsort3" => !empty($v->jobsort3) ? $v->jobsort3 : '',
                "jobsort4" => !empty($v->jobsort4) ? $v->jobsort4 : '',
                "jobsort5" => !empty($v->jobsort5) ? $v->jobsort5 : '',
                "jobarea1" => !empty($v->jobarea1) ? $v->jobarea1 : '',
                "jobarea2" => !empty($v->jobarea2) ? $v->jobarea2 : '',
                "jobarea3" => !empty($v->jobarea3) ? $v->jobarea3 : '',
                "jobarea4" => !empty($v->jobarea4) ? $v->jobarea4 : '',
                "jobarea5" => !empty($v->jobarea5) ? $v->jobarea5 : '',
                "industry1" => !empty($v->industry1) ? $v->industry1 : '',
                "industry2" => !empty($v->industry2) ? $v->industry2 : '',
                "industry3" => !empty($v->industry3) ? $v->industry3 : '',
                "industry4" => !empty($v->industry4) ? $v->industry4 : '',
                "industry5" => !empty($v->industry5) ? $v->industry5 : '',
                "sex" => !empty($v->sex) ? $v->sex : '',
                "age" => !empty($v->age) ? $v->age : '',
                "education" => !empty($v->education) ? $v->education : '',
                "work_year" => !empty($v->work_year) ? $v->work_year : '',
                "keyword" => !empty($v->keyword) ? $v->keyword : '',
                "keyword_type" => !empty($v->keyword_type) ? $v->keyword_type : '',
                "release_date" => !empty($v->release_date) ? $v->release_date : '',
            ));
            //设置a连接属性
            $search = '';
            foreach($alinks as $kk => $vv){
                $search .= $kk . '=' . $vv . '&';
            }
            $search = '?' . trim($search, '&');
            $v->search_link = asset('job' . $search);
        }
        return Style::view('personal.searchIndex', compact('searchEngine'));
    }

    /**
     * 添加搜索器
     * @return mixed
     */
    public function create(){
        return Style::view('personal.searchCreate');
    }

    /**
     * 添加搜索器提交
     * @param CreateSearchEngineRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(CreateSearchEngineRequest $request){
        $user = auth()->guard('personal')->user();
        $input = $request->except('_token', 'workplace', 'jobsort', 'industry', 'sub');
        $input['uid'] = $user->uid;
        SearchEngine::create($input);
        return redirect('personal/search');
    }

    /**
     * 编辑搜索器
     * @param $id
     * @return mixed
     */
    public function edit($id){
        $user = auth()->guard('personal')->user();
        $searchEngine = SearchEngine::where('uid', $user->uid)->find($id);
        //工地地区
        $jobarea1 = (strlen($searchEngine->jobarea1) == 8) ? CollTown::getTownName($searchEngine->jobarea1) : CollArea::getAreaName($searchEngine->jobarea1);
        $jobarea2 = (strlen($searchEngine->jobarea2) == 8) ? CollTown::getTownName($searchEngine->jobarea2) : CollArea::getAreaName($searchEngine->jobarea2);
        $jobarea3 = (strlen($searchEngine->jobarea3) == 8) ? CollTown::getTownName($searchEngine->jobarea3) : CollArea::getAreaName($searchEngine->jobarea3);
        $jobarea4 = (strlen($searchEngine->jobarea4) == 8) ? CollTown::getTownName($searchEngine->jobarea4) : CollArea::getAreaName($searchEngine->jobarea4);
        $jobarea5 = (strlen($searchEngine->jobarea5) == 8) ? CollTown::getTownName($searchEngine->jobarea5) : CollArea::getAreaName($searchEngine->jobarea5);
        $searchEngine->workplace = trim($jobarea1 . '+' . $jobarea2 . '+' . $jobarea3 . '+' . $jobarea4 . '+' . $jobarea5, '+');
        //工地岗位
        $jobsort1 = ($searchEngine['jobsort1']) ? CollPosition::getPosName($searchEngine['jobsort1']) : '';
        $jobsort2 = ($searchEngine['jobsort2']) ? CollPosition::getPosName($searchEngine['jobsort2']) : '';
        $jobsort3 = ($searchEngine['jobsort3']) ? CollPosition::getPosName($searchEngine['jobsort3']) : '';
        $jobsort4 = ($searchEngine['jobsort4']) ? CollPosition::getPosName($searchEngine['jobsort4']) : '';
        $jobsort5 = ($searchEngine['jobsort5']) ? CollPosition::getPosName($searchEngine['jobsort5']) : '';
        $searchEngine->jobsort = trim($jobsort1 . '+' . $jobsort2 . '+' . $jobsort3 . '+' . $jobsort4 . '+' . $jobsort5, '+');
        //工地岗位
        $industry1 = CollOption::getOptionName($searchEngine['industry1'], 'industry');
        $industry2 = CollOption::getOptionName($searchEngine['industry2'], 'industry');
        $industry3 = CollOption::getOptionName($searchEngine['industry3'], 'industry');
        $industry4 = CollOption::getOptionName($searchEngine['industry4'], 'industry');
        $industry5 = CollOption::getOptionName($searchEngine['industry5'], 'industry');
        $searchEngine->industry = trim($industry1 . '+' . $industry2 . '+' . $industry3 . '+' . $industry4 . '+' . $industry5, '+');
        return Style::view('personal.searchUpdate', compact('searchEngine'));
    }

    /**
     * 更新搜索器
     * @param UpdateSearchEngineRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(UpdateSearchEngineRequest $request, $id){
        $user = auth()->guard('personal')->user();
        $input = $request->except('_token', '_method', 'workplace', 'jobsort', 'industry', 'sub');
        $result = SearchEngine::where('id', $id)->where('uid', $user->uid)->update($input);
        if($result){
            //flash('更新搜索器成功', 'success');
            return redirect('personal/search');
        }else{
            return back()->with('errors', '搜索器信息更新失败，请稍后重试！');
        }
    }

    /**
     * 删除搜索器
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function destroy(Request $request, $id){
        $user = auth()->guard('personal')->user();
        $result = SearchEngine::where('id', $id)->where('uid', $user->uid)->delete();
        if($result){
            return response()->json(['status' => 0, 'msg' => '搜索器删除成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '搜索器删除失败，请稍后重试！']);
        }
    }

    /**
     * 推荐给您的职位
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function recommendedPost(Request $request){
        $user = auth()->guard('personal')->user();
        $similarJobs = [];
        $resume = Resume::where('uid', $user->uid)
            ->select('id','intentionjobs', 'jobsort1',
                'jobsort2', 'jobsort3', 'jobsort4', 'jobsort5')
            ->first();
        if($resume){
            if(\Site::get('xsOpen')){
                $similarJobs = $this->xunCommend($resume,$request);
                if ($similarJobs->total() < 1); $similarJobs = $this->sqlCommend($resume,$request);
            }else{
                //从mysql原来的方法中找出推荐职位
                $similarJobs = $this->sqlCommend($resume,$request);
            }
            //推荐给您的职位
            return Style::view('personal.recommendedPost', compact('similarJobs'));
        }else{
            return redirect('personal/resume_refresh');
        }
    }

    /** 迅搜推荐
     * @param $resume
     * @param $request
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    public function xunCommend($resume, $request)
    {
        //从xunsearch讯搜中找出推荐职位
        $q=[];

        $jobarea=[];//工作地点
        $jobsort=[];//所属岗位
        for ($i=1;$i<=5;$i++) {
            $area=$resume->{'jobarea' . $i};
            $sort=$resume->{'jobsort' . $i};
            if (!empty($area)) {
                $jobarea[]=$area;
            }
            if (!empty($sort)) {
                $jobsort[]=$sort;
            }
        }
        $q['jobarea']=$jobarea;
        $q['jobsort']=$jobsort;

        $keyword = [];
        $keyword[] = $resume->intentionjobs;//意向岗位
        $q['keyword'] = $keyword;
        $q['by_day'] = true;

        $jobxs = new JobXS();
        $page = $request->input('page', 1);
        //搜索(参数:搜索条件,第几页,一页个数,获取总数,是否按照时间排序)
        $arr = $jobxs->searchJob($q, $page,18,true,true);
        return $this->pageInfo($arr['data'],$arr['total'],$request);
    }

    /** sql推荐
     * @param $resume
     * @return mixed
     */
    public function sqlCommend($resume,$request)
    {
        $job = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->select(
                't1.job_title', 't1.id', 't1.com_id', 't1.salary_above', 't1.salary_below', 't1.updatetime',
                't2.company_name'
            )
            ->where('job_status', 1)//审核通过的职位
            ->where(function($query) use ($resume){
                for($i = 1; $i <= 5; $i++){
                    $value = $resume->{'jobsort' . $i};
                    if (!empty($value)) {
                        $query->orWhere('t1.job_category1', '=', $value)
                            ->orWhere('t1.job_category2', '=', $value)
                            ->orWhere('t1.job_category3', '=', $value)
                            ->orWhere('t1.job_category4', '=', $value)
                            ->orWhere('t1.job_category5', '=', $value);
                    }
                }
            });
        $count = $job->count();
        $jobs = $job->orderBy('t1.updatetime', 'desc')->orderBy('t1.id','desc')
            ->skip($this->getSkip($request->page))->take(18)->get();
        return $this->pageInfo($jobs,$count,$request);
    }

    /**
     * 分页信息
     */
    protected function pageInfo($data,$total,$request){
        $perPage = 18;//每页显示18条
        $current_page = $request->input('page',1);
        $total=$total>(18*200)?(18*200):$total;
        $company_job = new LengthAwarePaginator($data, $total, $perPage, $current_page,[
            'path' => Paginator::resolveCurrentPath(), //注释2
            'pageName' => 'page',
        ]);
        return $company_job;
    }

    /**
     * 取得分页启始数
     */
    protected function getSkip($page){
        if(empty($page)) $page=1;
        if($page>200) $page=200;
        return ($page-1)*18;
    }
}